package com.test.util;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import com.zyncro.api.IDepartmentApiService;

public final class PackageGenerator {

	private PackageGenerator() {

	}

	public static void main(String[] args) {

		String packageName = "com.api.department";
		Class<?> aClass = IDepartmentApiService.class;

		File baseDirectory = getBaseDirectory(packageName);

		Map<String, Integer> methodsMap = getMethodsSubCount(aClass);

		for (Entry<String, Integer> method : methodsMap.entrySet()) {

			String name = method.getKey().toLowerCase();
			int count = method.getValue();

			String folderPath = baseDirectory.getAbsolutePath() + File.separator + name;
			File newFolder = new File(folderPath);
			newFolder.mkdir();

			for (int i = 0; i < count; i++) {

				String subFolderPath = newFolder.getAbsolutePath() + File.separator + "p" + String.valueOf(i + 1);
				new File(subFolderPath).mkdir();
			}
		}
	}

	private static File getBaseDirectory(String packageName) {

		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
		String path = packageName.replace('.', '/');
		try {
			Enumeration<URL> resources = classLoader.getResources(path);

			File directory = null;
			while (resources.hasMoreElements() && directory == null) {

				URL resource = resources.nextElement();
				File dir = new File(resource.getFile());
				if (dir.isDirectory()) {
					directory = dir;
				}
			}
			if (directory != null) {
				return directory;
			} else {
				throw new IllegalStateException(String.format("Couln't get base directory for package '%s'", packageName));
			}
		} catch (IOException ex) {
			throw new IllegalStateException(String.format("Couln't get base directory for package '%s'", packageName), ex);
		}
	}

	private static Map<String, Integer> getMethodsSubCount(Class<?> apiClass) {

		Map<String, Integer> map = new HashMap<String, Integer>();

		Method[] methods = apiClass.getDeclaredMethods();
		for (Method method : methods) {

			String name = method.getName();

			if (map.containsKey(name)) {
				int count = map.get(name);
				count++;
				map.put(name, count);
			} else {
				map.put(name, 0);
			}
		}

		return map;
	}
}
